package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.article.entity.ApArticle;
import com.heima.article.service.IPublishService;
import com.heima.common.minio.MinIOService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;


@Service
public class IPublishServiceImpl implements IPublishService {

    @Autowired
    private Configuration cfg;
    @Autowired
    private ApArticleServiceImpl apArticleService;
    @Autowired
    private MinIOService minIOService;
    /**
     * 生成静态页面
     *
     * @param apArticle
     * @param content
     */
    @Override
    public void createHtml(ApArticle apArticle, String content) {
        // 通过模板引擎freemarker创建html页面
        // 获取模板
        try {
            Template template = cfg.getTemplate("article.ftl");
            //获取数据
            Map map=new HashMap();
            map.put("content", JSON.parseArray(content));
            // 合并模板和数据
            StringWriter sw=new StringWriter();
            template.process(map,sw);
            // 将html页面上传到minio中
            String url="";
            // url地址文章id.html
            String name=apArticle.getId()+".html";
            // 将StringWriter 转换成输入流
            ByteArrayInputStream inputStream = new ByteArrayInputStream(sw.toString().getBytes());
            url=minIOService.upload(name,inputStream,"text/html");
            // 将返回的url地址保存到文章表中
            apArticle.setStaticUrl(url);
            apArticleService.updateById(apArticle);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
